package com.nwpu.intimacy.baidumapsdk.model;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class CacheUtil {

	public static void WriteToFile(String name, Bitmap bitmap, String path)
			throws IOException {
		String fString = name.replaceAll("/", ".");

		File dir = new File("/sdcard/Intimacy/user/" + path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File f = new File("/sdcard/Intimacy/user/" + path + "/" + fString
				+ ".png");
		f.createNewFile();
		FileOutputStream fOut = null;
		try {
			fOut = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
		try {
			fOut.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			fOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static Bitmap GetFromFile(String fileName, String path) {
		String fString = fileName.replaceAll("/", ".");
		File file = new File("/sdcard/Intimacy/user/" + path + "/" + fString
				+ ".png");
		if (!file.exists()) {
			return null;
		}
		try {

			FileInputStream fis = new FileInputStream(file);
			return BitmapFactory.decodeStream(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void writeToFile(String content, String type, String path)
			throws IOException {

		File dir = new File("/sdcard/Intimacy/user/" + path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File f = new File("/sdcard/Intimacy/user/" + path + "/" + type + ".txt");
		if (f.exists()) {
			f.delete();
		}
		f.createNewFile();
		FileWriter fw = new FileWriter(f);
		fw.write(content);
		fw.flush();
		fw.close();
	}

	public static String getFromFile(String type, String path)
			throws IOException {

		File f = new File("/sdcard/Intimacy/user/" + path + "/" + type + ".txt");
		if (!f.exists()) {
			return "";
		}
		String content = ""; // 文件内容字符串

		InputStream instream = new FileInputStream(f);
		if (instream != null) {
			InputStreamReader inputreader = new InputStreamReader(instream);
			BufferedReader buffreader = new BufferedReader(inputreader);
			String line;
			// 分行读取
			while ((line = buffreader.readLine()) != null) {
				content += line;
			}
			instream.close();
		}

		return content;
	}
}
